<?php
/**
 * 管理员模型
 * AdminMember.php
 * ==============================================
 * 版权所有 2013-2014
 * ----------------------------------------------
 * 这不是一个自由软件，未经授权不许任何使用和传播。
 * ----------------------------------------------
 * 
 * @package xcs
 * @author Huangdaohai <huangdaohai.2007@163.com>
 * @version $Id$
 * @access public
 */
class AdminMember extends AdminModel
{
	const ACTIVE_0=0;//未激活
	const ACTIVE_1=1;//激活
	public $password2;
    public $sManagerCacheFileName = '';
    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return AdminMember the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{admin_member}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('salt, username, password', 'required','message'=>'{attribute}不能为空'),
            array('username', 'match','pattern'=>'/^[^\s]{2,15}$/','on'=>'register','message'=>'请录入2-15位的中文、字母、数字或者下划线'),
            array('email', 'email','on'=>array('register','forget'),'message'=>'请输入正确的电子邮件'),
            array('email', 'required','on'=>'register','message'=>'{attribute}不能为空'),
            array('password2', 'required','on'=>array('register','editpass','editpersonpass'),'message'=>'{attribute}不能为空'),
			array('username,email', 'unique','on'=>array('register','update'),'message'=>'你输入的{attribute}已经存在'),
			array('password, password2', 'length','on'=>array('register','editpass','editpersonpass'), 'min'=>6, 'max'=>15,'tooLong'=>'你输入的密码太短','tooShort'=>'请录入6-15位密码'),
			array('password2', 'compare', 'compareAttribute'=>'password','message'=>'两次输入的密码不相同!','on'=>array('register','editpass','editpersonpass')),
			array('password', 'encryptPassword','on'=>array('register','editpass' ,'editpersonpass')),
            array('isactive', 'numerical', 'integerOnly'=>true),
            array('email', 'length', 'max'=>100),
            array('role_id', 'length', 'max'=>255),
            array('salt', 'length', 'max'=>5),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('uid, username, password, role_id, email, salt, password2 , isactive', 'safe', 'on'=>'search'),
        );
    }
    //检测验证的路径是否正确
    public static function checkSign($arr,$sign,$salt){
		//s
		$sginkey = "";
		foreach ($arr as $k=>$v)
		{
			$sginkey .= $v;
		}
		$sginkey = md5(md5($sginkey).$salt);
		if($sginkey==$sign)
			return true;
		else 
			return false;
	}
	//制作邮箱激活的链接
    public static function makeKey($ca,$arr,$salt)
	{	//s
		$sign = "";
		foreach ($arr as $k=>$v)
		{
			$sign .= $v;
		}
		$sign = md5(md5($sign).$salt);
	    $arr['sign'] = $sign;
	    return Yii::app()->request->hostInfo.Yii::app()->createUrl($ca,$arr);
	}
	
    public function encryptPassword($attribute,$params){
		$this->password=md5(md5($this->password).$this->salt);
	}
	
    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
			'user_role' => array(self::BELONGS_TO,'AdminRole','','on' => 't.role_id=user_role.role_id','select'=>'role_name,action_list,status'),	
		);
    }
    /**
     * AdminMember::getAllManager()
     * 
     * @return
     */
    public function getAllManager(){
        $aData = Yii::app()->filecache->get($this->sManagerCacheFileName);
        
        if( empty( $aData ) ){
            return $this->updateAllMemberCache();
        } else {
            return $aData;
        }
	}
    private function updateAllMemberCache(){
        //$sManagerCacheFileName
        $aData = $aTemp = array();
		$criteria = new CDbCriteria();
		$criteria->condition = "isactive=1"; 
        //$criteria->condition = "isactive=1 AND uid!=1"; 
		$oResult = self::model()->with('user_role')->findAll($criteria);
		if( $oResult ){
            foreach( $oResult as $aVal ){
                $aTemp['uid'] = $aVal->uid;
                $aTemp['username'] = $aVal->username;
                $aTemp['role_id'] = $aVal->role_id;
                $aData[$aVal->uid] = $aTemp;
            }
		}
		Yii::app()->filecache->set($this->sManagerCacheFileName ,$aData);
		return $aData;
    }
    /**
     * AdminMember::getManagerInfoByUid()
     * 
     * @param mixed $uid 1,2,3  or array(1,2,3);
     * @return
     */
    public function getManagerInfoByUid($uid){        
        $aData = $aTemp = array();
        if( empty( $uid ) ) return $aData;
        if(is_string($uid) && strpos($uid ,',')>=0 ) $uid = explode(',' ,$uid);
        $sName = '';
		$oResult = $this->getAllManager();
		if( $oResult && $uid ){
		    for( $i=0 ;$i<count($uid) ; $i++ ){
		      if( isset($oResult[$uid[$i]]) ){
		          $aTemp['uid'] = $oResult[$uid[$i]]['uid'];
                  $aTemp['username'] = $oResult[$uid[$i]]['username'];
                  $aTemp['role_id'] = $oResult[$uid[$i]]['role_id'];
                  $sName .= $oResult[$uid[$i]]['username'] .',';
                  $aData[] = $aTemp;
		      }
		    }
		}
		$aData['sName'] = Yii::app()->common->cutstr($sName,mb_strlen($sName ,'utf-8')-1 ,0 ,'');
		return $aData;
	}
    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
        	'uid' => 'ID',
			'username' => '账号',
			'password' => '密码',
			'password2' => '确认密码',
			'salt' => '密钥',
            'email' => '电子邮件',
            'isactive' => '是否已经激活',
            'last_login_time' => '最后登录时间' ,
            'role_id' => '所属角色',
            'oldpass'=>'旧密码'
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('uid',$this->uid);
        $criteria->compare('username',$this->username,true);
        $criteria->compare('password',$this->password,true);
        $criteria->compare('email',$this->email,true);
        $criteria->compare('salt',$this->salt,true);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }
    //部门id转部门名称
    public static function part_ids_to_name($part_ids){
    	if (empty($part_ids)) return false;
    	$sql = 'select * from {{admin_partment}} where part_id in('.$part_ids.')';
    	$result = Yii::app()->db->createCommand($sql)->queryAll();
    	$part_names = array();
    	foreach ($result as $v){
    		$part_names[] = $v['part_name'];
    	}
    	return join(',',$part_names);
    }
} 